package com.zzyl.service.impl;

import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.CustomerMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.CustomerService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Service
public class CustomerServiceImpl implements CustomerService {


    @Autowired
    private WeChatService weChatService;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    /**
     * c端用户登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {

        //查询用户的openID
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());
        //查询用户的手机号
        String phoneNumber = weChatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        //根据OpenID查询数据库
        Member member = customerMapper.getByOpenId(openId);
        //如果返回结果为空，则为新用户，创建新用户并设置属性插入数据库（名字也要赋值）
        if (member == null){
            member = new Member();
            member.setPhone(phoneNumber);
            member.setName(getRandomName() + "_" + phoneNumber.substring(7));
            member.setOpenId(openId);
            customerMapper.insert(member);
        }
        //如果不是新用户，则直接从用户中获取名称
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(member.getName());
        //生成对应的JWT令牌，从用户中获取ID并且设置进入JWT令牌中。
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",member.getId());
        map.put("nickName",member.getName());
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey()
                , jwtTokenManagerProperties.getTtl(), map);
        loginVo.setToken(token);
        return loginVo;
    }
    private String getRandomName(){
        List<String> nameList = List.of("生活更美好",
                "大桔大利",
                "日富一日",
                "好柿开花",
                "柿柿如意",
                "一椰暴富",
                "大柚所为",
                "杨梅吐气",
                "天生荔枝");
        return nameList.get(new Random().nextInt(nameList.size()));
    }
}
